from flask import request, current_app
from flask_jwt_extended import jwt_required
from . import role_bp
from ..services.role_service import RoleService
from ..utils.response import success_response, error_response
from ..middlewares.permission import check_permission

@role_bp.route('', methods=['GET'])
@jwt_required()
@check_permission()
def get_roles():
    """获取角色列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('size', 10, type=int)
        keyword = request.args.get('keyword', None, type=str)
        
        result = RoleService.get_role_list(page=page, per_page=per_page, keyword=keyword)
        return success_response(data=result)
    except Exception as e:
        current_app.logger.error(f"获取角色列表失败: {str(e)}")
        return error_response(message="获取角色列表失败")

@role_bp.route('', methods=['POST'])
@jwt_required()
@check_permission()
def create_role():
    """创建角色"""
    try:
        data = request.get_json()
        if not data or not data.get('role_name') or not data.get('role_code'):
            return error_response(message="角色名称和角色代码不能为空")
        
        # 检查角色代码是否已存在
        if RoleService.get_role_by_code(data['role_code']):
            return error_response(message="角色代码已存在")
        
        role = RoleService.create_role(data)
        return success_response(message="创建成功", data=role.to_dict())
    except Exception as e:
        current_app.logger.error(f"创建角色失败: {str(e)}")
        return error_response(message="创建角色失败")

@role_bp.route('/<int:id>', methods=['GET'])
@jwt_required()
@check_permission()
def get_role(id):
    """获取指定角色详情"""
    try:
        role = RoleService.get_role_by_id(id)
        if not role:
            return error_response(message="角色不存在", code=404)
        return success_response(data=role.to_dict())
    except Exception as e:
        current_app.logger.error(f"获取角色详情失败: {str(e)}")
        return error_response(message="获取角色详情失败")

@role_bp.route('/<int:id>', methods=['PUT'])
@jwt_required()
@check_permission()
def update_role(id):
    """更新角色信息"""
    try:
        role = RoleService.get_role_by_id(id)
        if not role:
            return error_response(message="角色不存在", code=404)
        
        data = request.get_json()
        if not data:
            return error_response(message="更新数据不能为空")
        
        # 如果更新角色代码，需要检查是否已存在
        if 'role_code' in data and data['role_code'] != role.role_code:
            if RoleService.get_role_by_code(data['role_code']):
                return error_response(message="角色代码已存在")
        
        role = RoleService.update_role(role, data)
        return success_response(message="更新成功", data=role.to_dict())
    except Exception as e:
        current_app.logger.error(f"更新角色信息失败: {str(e)}")
        return error_response(message="更新角色信息失败")

@role_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
@check_permission()
def delete_role(id):
    """删除角色"""
    try:
        role = RoleService.get_role_by_id(id)
        if not role:
            return error_response(message="角色不存在", code=404)
        
        RoleService.delete_role(role)
        return success_response(message="删除成功")
    except Exception as e:
        current_app.logger.error(f"删除角色失败: {str(e)}")
        return error_response(message="删除角色失败")

@role_bp.route('/<int:id>/status', methods=['PATCH'])
@jwt_required()
@check_permission()
def update_role_status(id):
    """修改角色状态"""
    try:
        role = RoleService.get_role_by_id(id)
        if not role:
            return error_response(message="角色不存在", code=404)
        
        data = request.get_json()
        if 'status' not in data:
            return error_response(message="状态参数不能为空")
        
        role = RoleService.update_role_status(role, data['status'])
        return success_response(message="状态更新成功", data={"status": role.status})
    except Exception as e:
        current_app.logger.error(f"更新角色状态失败: {str(e)}")
        return error_response(message="更新角色状态失败") 